import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { Doctor } from './entities/doctor.entity';
import { CreateDoctorDto } from './dto/create-doctor.dto';
import { UpdateDoctorDto } from './dto/update-doctor.dto';
import { log } from 'console';

@Injectable()
export class DoctorService {
  constructor(
    @InjectRepository(Doctor)
    private readonly doctorRepository: Repository<Doctor>,
  ) {}

  async create(createDoctorDto: CreateDoctorDto) {
    const doctor = this.doctorRepository.create(createDoctorDto);
    return this.doctorRepository.save(doctor);
  }

  async findAll() {
    return this.doctorRepository.find({
      where: { status: 'approved' },
      relations: ['user'],
    });
  }

  async findOne(id: number) {
    const doctor = await this.doctorRepository.findOne({
      where: { id },
      relations: ['user'],
    });
    if (!doctor) {
      throw new NotFoundException('医生信息不存在');
    }
    return doctor;
  }

  async update(id: number, updateDoctorDto: UpdateDoctorDto) {
    const doctor = await this.findOne(id);
    this.doctorRepository.merge(doctor, updateDoctorDto);
    return this.doctorRepository.save(doctor);
  }

  async remove(id: number) {
    const doctor = await this.findOne(id);
    return this.doctorRepository.remove(doctor);
  }

  // 管理员获取医生列表，可根据状态筛选
  async getDoctorList(query: any = {}) {
    const { page = 1, size = 10, status = '' } = query;
    const searchObj = {
      // 根据关键词模糊查询
      where: {
        ...(status && { status }),
      },
      // 根据分页信息查询
      skip: (page - 1) * size, // 从第x页开始，需要x条数据
      take: size,
      relations: ['user'], // 关联用户信息
    };

    const totalNum = {
      where: {
        ...(status && { status }),
      },
    };

    const data = await this.doctorRepository.find(searchObj);
    const total = await this.doctorRepository.count(totalNum);
    // 从数据库中获取结果，并作为响应返回
    return {
      data,
      total,
    };
  }
}
